#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Introduction to Programming in Java - An Interdisciplinary Approach

All book programs ported to Python by
Scott C. King (revisionx at {gee}ma1l <dot> c0m).

All program examples pass Pylint with a perfect 10.00 score.
Pylint:  http://www.pylint.org/


Program 1.4.3 - Sieve of Eratosthenes

Syntax:
python primesieve.py 1000


Notes:
int(sys.argv[1]) == Integer.parseInt(args[0])

sys is a required import here in order to use command line arguments.
https://docs.python.org/2/tutorial/stdlib.html

If you attempt the example 1000000000 given in the book, go get some coffee!
(Took almost 11 minutes on my Xeon workstation...)

'''

import sys
import time


def main():
    ''' Compute primes less than or equal to N '''

    try:
        prime_range = int(sys.argv[1])
    except IndexError:
        print 'Integer for primes range is required!'
        print 'Syntax: "python primesieve.py 100"'
        sys.exit(0)

    start_time = time.time()

    is_prime = range(prime_range + 1)
    for index in is_prime:
        is_prime[index] = True

    # Alternate (list comprehension)
    # is_prime = [True for _ in range(prime_range + 1)]

    for value in range(2, (prime_range/2) + 1):
        if is_prime[value]:
            for multiple in range(value, (prime_range/value) + 1):
                is_prime[multiple * value] = False

    primes = 0
    for item in range(2, len(is_prime)):
        if is_prime[item] == True:
            primes += 1
    print primes

    stop_time = time.time()
    total_time = stop_time - start_time
    print '{}m {}s to complete'.format(int(total_time/60), int(total_time % 60))

if __name__ == '__main__':
    main()
